package com.czl.module_storehouse.activity.remand.scan;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.czl.base.data.bean.tengyun.BorrowBean;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.ReceiveBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.activity.base.BaseOperationLocationActivity;
import com.czl.module_storehouse.activity.scan.ScanActivity;
import com.czl.module_storehouse.adapter.RemandScanAdapter;
import com.czl.module_storehouse.adapter.tree.ListTree;
import com.czl.module_storehouse.bean.RemandBean;
import com.czl.module_storehouse.databinding.ActivityRemandScanBinding;
import com.czl.module_storehouse.event.AllocateScanBackEvent;
import com.czl.module_storehouse.event.RemandScanEvent;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.presenter.StorehouseLocationPresenter;
import com.czl.module_storehouse.mvp.view.StorehouseLocationView;
import com.czl.module_storehouse.utils.QrCodeRuleUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashSet;
import java.util.List;

/**
 * @author xubin
 */
public class RemandScanActivity extends BaseOperationLocationActivity<ActivityRemandScanBinding> implements StorehouseLocationView,
        SimpleView {
    private static final int OPERATION_REPLACE = 0x13;

    public static final int TAG_RETURN = 0;

    private final ListTree mListTree = new ListTree();
    protected SortBean mSortBean;
    protected RemandScanAdapter mAdapter;
    private List<ProductBean> mReceiveProductViewList;
    private List<ProductBean> mBorrowProductViewList;
    private ListTree.TreeNode mTreeNode;
    protected final HashSet<Integer> mSelectProductIds = new HashSet<>();
    private int mOperationType;
    @InjectPresenter
    ProductPresenter mProductPresenter;
    @InjectPresenter
    StorehouseLocationPresenter mStorehouseLocationPresenter;

    @Override
    protected ActivityRemandScanBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityRemandScanBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("物品归还");
        EventBus.getDefault().register(this);
        mAdapter = new RemandScanAdapter(mListTree, mSelectedSet);
        binding.recyclerView.setAdapter(mAdapter);
        if (!interruptInitData()) {
            initDataAtSort(mSortBean);
        }
        binding.headerRemand.textScan.setOnClickListener(v -> goScanActivity());
        binding.textReturn.setOnClickListener(v -> submit(TAG_RETURN));
        binding.headerRemand.textSaveLoc.setOnClickListener(v -> {
            mOperationType = 0;
            getStorehouseLocatList(true);
        });
        initListener();
    }

    protected void initDataAtSort(SortBean sortBean) {
        List<LocatListBean> locatList = null;
        if (sortBean != null) {
            mSortBean = ParcelHelper.copy(sortBean);
            binding.headerRemand.tvTitleNum.setText(mSortBean.getSortName());
            locatList = mSortBean.getLocatList();
        }
        if (locatList != null) {
            binding.textReturn.setEnabled(true);
            mAdapter.addAll(locatList, mSelectProductIds);
            for (LocatListBean bean : locatList) {
                mSelectedSet.add(bean.getStorehouseLocatId());
            }
        } else if (!mSelectedSet.contains(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID))) {
            LocatListBean locatListBean = new LocatListBean();
            locatListBean.setStorehouseLocatName("默认位置");
            locatListBean.setStorehouseLocatId(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID));
            locatListBean.setSelected(true);
            mAdapter.add(locatListBean);
            mSelectedSet.add(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID));
        }
    }

    protected boolean interruptInitData() {
        return false;
    }

    protected boolean isTextEnable() {
        return false;
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(RemandScanEvent event) {
        mSortBean = event.getSortBean();
        RemandBean remandBean = event.getRemandBean();
        if (remandBean != null) {
            ReceiveBean receiveBean = remandBean.getReceiveBean();
            if (receiveBean != null) {
                mReceiveProductViewList = receiveBean.getReceiveProductViewList();
            }
            BorrowBean borrowBean = remandBean.getBorrowBean();
            if (borrowBean != null) {
                mBorrowProductViewList = borrowBean.getBorrowProductViewList();
            }
        }
    }

    protected void initListener() {
        mAdapter.setOnItemClickListener((treeNode, position) -> {
            mOperationType = OPERATION_REPLACE;
            mTreeNode = treeNode;
            //选择位置
            getStorehouseLocatList(true);
        });
        mAdapter.setOnProductChangeListener(new RemandScanAdapter.OnProductChangeListener() {
            @Override
            public void add(ProductBean bean, int count) {
                if (isTextEnable()) {
                    binding.textReturn.setEnabled(count > 0);
                }
                mSelectProductIds.add(bean.getProductId());
                mSelectedSet.add(bean.getStorehouseLocatId());
            }

            @Override
            public void remove(ProductBean bean, int count) {
                if (isTextEnable()) {
                    binding.textReturn.setEnabled(count > 0);
                }
                mSelectProductIds.remove(bean.getProductId());
            }
        });
    }

    protected boolean setResultProduct(ProductBean productBean) {

        if (mSortBean != null) {
            if (!productBean.isSortProduct(mSortBean.getSortId())) {
                showToast("不是该归还物品");
                return true;
            }
        }

        if (mBorrowProductViewList != null) {
            if (!productBean.isReturnProduct(mBorrowProductViewList)) {
                showToast("该物品不是待归还物品");
                return true;
            }
        }
        if (mReceiveProductViewList != null) {
            if (!productBean.isReturnProduct(mReceiveProductViewList)) {
                showToast("该物品不是待归还物品");
                return true;
            }
        }

        if (!productBean.isRemand()) {
            showToast("该物品不是待归还物品");
            return true;
        }
        return false;
    }

    protected ProductPresenter getProductPresenter() {
        return mProductPresenter;
    }

    protected void getProductUseInfoByCode(String productCode) {
        getProductPresenter().getProductUseInfoByCode(productCode);
    }

    protected void getProductInfo(String productId) {
        getProductPresenter().getProductUseInfo(Integer.parseInt(productId));
    }

    protected void submit(int reqestTag) {
        AllocateScanBackEvent event = new AllocateScanBackEvent();
        if (mAdapter != null && mSortBean != null) {
            List<LocatListBean> locatList = mAdapter.getlocatList();
            mSortBean.setLocatList(locatList);
            event.setSortBean(mSortBean);
        }
        EventBus.getDefault().postSticky(event);
        finish();
    }

    private void getSelectedList() {
        ListTree tree = mAdapter.getTree();
        if (tree == null) {
            return;
        }
        List<ListTree.TreeNode> nodes = tree.getNodes();
        for (ListTree.TreeNode node : nodes) {
            Object data = node.getData();
            if (data == null) {
                continue;
            }
            if (data instanceof LocatListBean) {
                LocatListBean locatListBean = (LocatListBean) data;
                if (SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID) == locatListBean.getStorehouseLocatId()) {
                    continue;
                }
                mSelectedSet.add(locatListBean.getStorehouseLocatId());
            }
        }
    }

    @Override
    protected boolean callBackModel(LocatListBean bean) {
        boolean call = super.callBackModel(bean);
        if (!call) {
            showToast("该库位已添加");
            return false;
        }
        if (OPERATION_REPLACE == mOperationType) {
            //更改位置
            Object data = mTreeNode.getData();
            if (data instanceof LocatListBean) {
                int locatId = ((LocatListBean) data).getStorehouseLocatId();
                mSelectedSet.remove(locatId);
            }
            mAdapter.set(mTreeNode, bean);
        } else {
            mAdapter.add(bean);
        }
//        getSelectedList();
        return true;
    }

    protected final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getData() != null) {
                    String stringResult = result.getData().getStringExtra(ScanActivity.RESULT);
                    getProductUseInfoByCode(QrCodeRuleUtils.handleStorehouseProductResult(stringResult));
                }
            });

    private void goScanActivity() {
        mLauncher.launch(new Intent(getContext(), ScanActivity.class));
    }

    @Override
    protected StorehouseLocationPresenter getLocationPresenter() {
        return mStorehouseLocationPresenter;
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (ProductPresenter.TAG_PRODUCT_USE_INFO_BY_CODE.equals(httpResponse.getRequestTag())) {
            ProductBean productBean = (ProductBean) httpResponse.getData();
            if (productBean == null) {
                showToast("物品信息错误");
                return;
            }
            if (!productBean.pasteCode()) {
                showToast("该物品不支持扫码调拨");
                return;
            }
            if (setResultProduct(productBean)) {
                return;
            }

            boolean add = mSelectProductIds.add(productBean.getProductId());
            if (add) {
                productBean.setManufactureDate(null);
                mAdapter.add(productBean, mAdapter.getSelectGroupNode());
                binding.textReturn.setEnabled(true);
            } else {
                showToast("该物品已添加");
            }
        }
    }
}
